package zookeeper

import (
	"fmt"
	"github.com/samuel/go-zookeeper/zk"
	"github.com/spf13/viper"
	"time"
)

type Zookeeper struct {
	conn        *zk.Conn
	connForHttp *zk.Conn
}

var z *Zookeeper

var (
	DefaultHost string = "127.0.0.1"
	DefaultPort string = "2181"
)
//func init() {
//	z = new(Zookeeper)
//}

// 完成初始化
func New() {
	zookeeper := new(Zookeeper)
	zookeeper.conn = zookeeper.connect()
	//ConnectForHttp 连接zookeeper,http web使用
	// 建立链接
	zookeeper.connForHttp = zookeeper.connectForHttp()

	z = zookeeper
}

//Connect 返回一个可用的zookeeper链接
func Connect() *zk.Conn {
	return z.conn
}

//Connect 连接zookeeper
func (z *Zookeeper) connect() *zk.Conn {
	hosts := z.getHosts()
	conn, _, err := zk.Connect(hosts, time.Second*time.Duration(viper.GetInt("zookeeper.session_timeout")))
	if err != nil {
		panic(err)
	}

	return conn
}

//ConnectForHttp 返回一个可用的zookeeper链接，http web使用
func ConnectForHttp() *zk.Conn {
	return z.connForHttp
}

//ConnectForHttp 连接zookeeper,http web使用
func (z *Zookeeper) connectForHttp() *zk.Conn {
	hosts := z.getHosts()
	// 建立链接  包函数Connect()与Zookeeper池中服务者建立新连接.
	// 第二个参数为sessionTimeout time.Duration,
	conn, _, err := zk.Connect(hosts, time.Second)
	if err != nil {
		_, _ = fmt.Println(err)
	}

	return conn
}

//getHost 获取host
// todo：这里需要优化为可以获取多个hosts，目前只能获取一个host
func (z *Zookeeper) getHosts() []string {
	host := viper.GetString("zookeeper.host")
	port := viper.GetString("zookeeper.port")

	if host == "" {
		// default
		host = "127.0.0.1"
	}
	if port == "" {
		port = "2181"
	}

	return []string{host + ":" + port}
}
